#include <string>
#include <vector>
using namespace std;
class Solution
{
public:
    int lengthOfLongestSubstringKDistinct(string s, int k)
    {
        int ans = s.size();
        int size = ans;
        int l = 0, r = 0;
        vector<int> charsCount(128, 0);
        int kinds = 0;
        while (r < size)
        {
            if (charsCount[s[r++]]++ <= 0)
            {
                kinds++;
            }
            if (kinds <= k)
            {
                ans = max(ans, r - l);
            }
            while (kinds > k)
            {
                if (--charsCount[s[l++]] <= 0)
                {
                    kinds--;
                }
            }
        }
    }
};